package com.galeno.day09.test;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

/**
 * @author galeno
 * @Title:
 * @Description:
 * @date 2021/10/2620:16
 */
public class ProcessStreamProcessFunction {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",12345);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
        //spark,1
        DataStreamSource<String> lines = env.socketTextStream("192.168.77.3", 9999);

        SingleOutputStreamOperator<Tuple2<String, Integer>> process = lines.process(new ProcessFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void processElement(String value, Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] words = value.split("\\s+");
                for (String word : words) {
                    out.collect(Tuple2.of(word, 1));
                }
            }
        });
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = process.keyBy(x -> x.f0);
        //调用keydProcessFunction
        SingleOutputStreamOperator<Tuple2<String, Integer>> process1 = keyedStream.process(new KeyedProcessFunction<String, Tuple2<String, Integer>, Tuple2<String, Integer>>() {

            private transient ValueState<ArrayList<Tuple2<String, Integer>>> listValueState;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<ArrayList<Tuple2<String, Integer>>> listValueStateDescriptor = new ValueStateDescriptor<>("list-state", TypeInformation.of(new TypeHint<ArrayList<Tuple2<String, Integer>>>() {
                }));
                listValueState = getRuntimeContext().getState(listValueStateDescriptor);


            }

            @Override
            public void processElement(Tuple2<String, Integer> value, Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                /**
                 * 在processElement中不输出数据,而是将数据攒起来,然后注册定时器
                 * 攒起来的数据最好放在状态中(可以容错)
                 */
                ArrayList<Tuple2<String, Integer>> tuple2ArrayList = listValueState.value();
                if (tuple2ArrayList == null) {
                    tuple2ArrayList = new ArrayList<>();
                }
                tuple2ArrayList.add(value);
                listValueState.update(tuple2ArrayList);
                //注册定时器
                //ctx.timerService().registerProcessingTimeTimer(System.currentTimeMillis() + 15000);

                //11:29:15 下一次触发的时间11：30：00
                //11:29:18 下一次触发的时间11：30：00
                long trggerTime = (System.currentTimeMillis() - System.currentTimeMillis() % 60000) + 60000;
                System.out.println(ctx.getCurrentKey() + "注册定时器时间为"
                        + simpleDateFormat.format(System.currentTimeMillis()) +
                        "定时器触发时间" + simpleDateFormat.format(trggerTime));
                ctx.timerService().registerProcessingTimeTimer(trggerTime);


            }
            //定时器触发后会调用onTimer方法（每个key都有单独的定时器，每个key的定时器触发了都会调用一个onTimer方法）

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                System.out.println("触发定时器时间为" + simpleDateFormat.format(timestamp));
                ArrayList<Tuple2<String, Integer>> tuple2ArrayList = listValueState.value();
                for (Tuple2<String, Integer> tuple2 : tuple2ArrayList) {
                    out.collect(tuple2);

                }
                tuple2ArrayList.clear();
            }
        });
        process1.print();
        env.execute();


    }
}
